import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {partBackOrderDealStatus, currency, partBackOrderStatus} from '../Enum';
import routes from './routes';
import {TABLE, DATETIME_FORMAT} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {getDetail} from './api';
import {injectIntl} from './intl';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import styles from './style.css';
const basePath = fetch.basePath || '';
const url = '/#/dcs/parts/partBackOrder/';
const urlOrder = '/#/dcs/parts/partSaleOrder/';
class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        code: '',
        dealerId: '',
        dealerCode: '',
        dealerName: '',
        brandId: '',
        status: undefined,
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok) {
                    const order = res.data.details[0];
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        details: res.data.details,
                        code: order.saleOrderCode,
                        dealerId: order.dealerId,
                        dealerCode: order.dealerCode,
                        dealerName: order.dealerName,
                        brandId: order.brandId,
                        status: order.status,
                    });
                } else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    render() {
        const {data, code, dealerId, dealerCode, dealerName, brandId, status} = this.state;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.confirmor) && hasPermissions(data.options, PERMISSION.confirmor))
            operations.push(<Button key="confirmor" href={`${basePath}${url}${this.props.id}/confirmor?code=${code}&dealerId=${dealerId}&dealerCode=${dealerCode}&dealerName=${dealerName}&brandId=${brandId}&status=${status}`} size="small">{
                formatMessage({
                    id: 'detailPanel.confirmor',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.close) && hasPermissions(data.options, PERMISSION.close))
            operations.push(<Button key="close" href={`${basePath}${url}${this.props.id}/close?code=${code}&dealerId=${dealerId}&dealerCode=${dealerCode}&dealerName=${dealerName}&brandId=${brandId}&status=${status}`} size="small">{
                formatMessage({
                    id: 'detailPanel.close',
                    defaultMessage: '关闭'
                })
            }</Button>);
        const colums = [{
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.brandCode',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandCode',
            render: (text, record) => (record.brandCode) + record.brandName
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code'
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.saleOrderCode',
                defaultMessage: '订单编号'
            }),
            dataIndex: 'saleOrderCode'
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.saleOrderTypeName',
                defaultMessage: '订单类型'
            }),
            dataIndex: 'saleOrderTypeName'
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.orderAmount',
                defaultMessage: 'PI金额'
            }),
            dataIndex: 'orderAmount',
            render: text => formatAmount(text)
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.orderDate',
                defaultMessage: '提报日期'
            }),
            dataIndex: 'orderDate',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: this.props.intl.formatMessage({
                id: 'detailPanel.column.status',
                defaultMessage: '缺货单状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(partBackOrderStatus, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.orderQuantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'orderQuantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.invoiceAmount',
                defaultMessage: '发票数量'
            }),
            dataIndex: 'invoiceAmount'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.invoiceCode',
                defaultMessage: '发票号'
            }),
            dataIndex: 'invoiceCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.nowMissAmount',
                defaultMessage: '当前缺件数量'
            }),
            dataIndex: 'nowMissAmount'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.stockAmount',
                defaultMessage: '已备货数量'
            }),
            dataIndex: 'stockAmount'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.notStockQuantity',
                defaultMessage: '未备货数量'
            }),
            dataIndex: 'notStockQuantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.cancelQuantity',
                defaultMessage: '取消数量'
            }),
            dataIndex: 'cancelQuantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.transforQuantity',
                defaultMessage: '转订单数量'
            }),
            dataIndex: 'transforQuantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.waitQuantity',
                defaultMessage: '等待数量'
            }),
            dataIndex: 'waitQuantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.dealStatus',
                defaultMessage: '处理状态'
            }),
            dataIndex: 'dealStatus',
            render: text => conventEnumValueToString(partBackOrderDealStatus, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.expectedArrivalDate',
                defaultMessage: '预计到货日期'
            }),
            dataIndex: 'expectedArrivalDate'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.reasonsOfRefusal',
                defaultMessage: '拒绝原因'
            }),
            dataIndex: 'reasonsOfRefusal'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.createTime',
                defaultMessage: '缺货单创建日期'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmorName',
                defaultMessage: '确认人'
            }),
            dataIndex: 'confirmorName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmTime',
                defaultMessage: '确认时间'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.examineConfirmorName',
                defaultMessage: '审核人'
            }),
            dataIndex: 'examineConfirmorName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.examineConfirmTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'examineConfirmTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.colseConfirmorName',
                defaultMessage: '关闭人'
            }),
            dataIndex: 'colseConfirmorName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.colseConfirmTime',
                defaultMessage: '关闭时间'
            }),
            dataIndex: 'colseConfirmTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmStatus',
                defaultMessage: '审核状态'
            }),
            dataIndex: 'confirmStatus'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.newPartOrderCode',
                defaultMessage: '转订单编号'
            }),
            dataIndex: 'newPartOrderCode',
            render: (text, record) => <a href={`${basePath}${urlOrder}${record.newPartOrderId}/detail`} target="_blank" rel="noopener noreferrer">
                {record.newPartOrderCode}</a>
        }, {
            title: formatMessage({
                id: 'detailPanel.column.replacePartRemark',
                defaultMessage: '替换信息备注'
            }),
            dataIndex: 'replacePartRemark'
        }];
        if(!this.props.isDealerUser) {
            colums.splice(2, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代ERP号'
                    }),
                    dataIndex: 'dealerCode',
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                }, {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerName',
                        defaultMessage: '总代名称'
                    }),
                    dataIndex: 'dealerName'
                }
            ]);
            colums.splice(13, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.deliveryBeforeAmount',
                        defaultMessage: '交付前发货数量'
                    }),
                    dataIndex: 'deliveryBeforeAmount'
                }, {
                    title: formatMessage({
                        id: 'detailPanel.column.missAmount',
                        defaultMessage: '交付时缺件数量'
                    }),
                    dataIndex: 'missAmount'
                }, {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.deliveryAfterAmount',
                        defaultMessage: '交付后发货数量'
                    }),
                    dataIndex: 'deliveryAfterAmount'
                }
            ]);
        }
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.partBackOrder',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col>
                        </Row>}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={this.state.details}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    permissions: PropTypes.array
};

import {connect} from 'react-redux';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
